package com.redis.test01;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * 作者: LCG
 * 日期: 2019/9/10 13:30
 * 描述:
 */
public class TestRedisLock {

    /**
     * 错误的写法
     * @param key
     * @param value
     * @param redisTemplate
     * @return
     */
    public static boolean lock(String key, String value, RedisTemplate redisTemplate){
        //第一步
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(key, value);

        //第二步
        if(aBoolean){
            redisTemplate.expire(key,60,TimeUnit.SECONDS);
        }

        return aBoolean;
    }


    public static boolean getLock(String key, String value, RedisTemplate stringRedisTemplate, String timeout){

        String lock="if redis.call('setNx',KEYS[1],ARGV[1]) ~= 1 then return 0 else if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('expire',KEYS[1],ARGV[2]) else return 0 end end";

        DefaultRedisScript<Long> redisScript=new DefaultRedisScript (lock,Long.class);

        Object execute = stringRedisTemplate.execute ( redisScript,Collections.singletonList (key), value ,"50");

        System.out.println(execute.toString());

        if("1".equals (execute.toString ())){
            return true;
        }else{
            return false;
        }

    }

}
